//index.js
import {formatTime} from '../../utils/util.js'
import {getLocation} from '../../utils/wxApi'
const regeneratorRuntime = require("../../utils/runtime")	//async插件
import Ajax from "../../utils/ajax" //ajax
const QQMapWX = require('../../utils/qqmap-wx-jssdk.min')	//腾讯地图组件
const app = getApp()


Page({
	
	/* 数据 */
	data: {
		date:formatTime(new Date()).split(" ")[0],
		startDate:formatTime(new Date()).split(" ")[0],	//开始日期
		endDate:formatTime(new Date(Date.now()+604800000)).split(" ")[0],	//结束日期（7天）
		fromTime:new Date().getHours()+":"+new Date().getMinutes(),		//开始时间
		toTime:new Date(Date.now()+3600000).getHours()+":"+new Date().getMinutes(),	//结束时间
		takeAddress:"",		//出发地点
		stationArr:["太原","榆次","原平","昔阳","阳泉","寿阳","阳曲","太谷","清徐","交城","文水"],	//始发站
		originIndex: 0,	//出发地
		destinationIndex: 0,	//目的地
	},
	
	/* 载入 */
	onLoad:async function () {
		//ajax
		this.ajax = new Ajax()
		
		//通过腾讯地图API获取当前地址
		let qqmapsdk = new QQMapWX({
			key: '2UKBZ-52M3U-SUEVI-B6W52-UI4AZ-XKBR5' // 必填
		}) 
		let self = this , location = await getLocation(app)
		qqmapsdk.reverseGeocoder({
			location,
			success(res){
				self.setData({
				  takeAddress: res.result.address,
				})
			},
			fail(error) {
	       	 	console.error(error);
				wx.showToast({
					icon:"none",
					title:error.message,
					duration:2000
				})
			}
		})
	},
	
	/* 上车点重置 */
	resetTakeAddress(){
		let self = this
		wx.chooseLocation({
			success(res) {
				if(res.address.length>1){
					self.setData({
					  takeAddress: res.name,
					})
				}
			}
		})
	},
	
	bindStationChange(e){	//站点下拉
		let type = e.target.dataset.type
		this.setData({
			[type]:e.detail.value
		})
	},
	
	/* 日期选择 */
	bindDateChange(e){
		this.setData({
			date:e.detail.value
		})
	},
	
	/* 时间选择 */
	bindTimeChange(e){
		this.setData({
			[e.target.dataset.type]:e.detail.value
		})
	},
	
	/* 预约按钮 */
	async bindOrderBtn(){
		wx.showLoading({title: 'Loading…'})		//loading
		if(app.globalData.dbUserData && app.globalData.dbUserData.userPhone.length>5){	//已经授权过
			let orderData = await this.ajax.post("car_trip_passenger/addByCarPassenger",{
				origin: this.data.stationArr[this.data.originIndex],	//出发地
				destination:this.data.stationArr[this.data.destinationIndex],	//目的地
				originPlace: this.data.takeAddress,		//出发详细地址
				remarks: "",
				setoutStarttime:this.data.startDate+" "+this.data.fromTime,
				setoutEndtime: this.data.endDate+" "+this.data.toTime,
				xiaoOpenId: app.globalData.openid
			})
			wx.hideLoading()  //关闭loading
			if(orderData.code==0){
				wx.showToast({
					title: '预约成功',
					duration: 2000
				})
			}else{
				wx.showToast({
					title: orderData.message,
					icon:"none",
					duration: 2000
				})
			}
		}else{	//未授权返回登录页
			wx.hideLoading()  //关闭loading
			wx.navigateTo({
				url: '/pages/login/login'
			})
		}
		
	},
	
	/* 返回页面重新加载数据 */
	onShow(){
		this.onLoad()
	}
})
